package v2

import (
	"git.multiverse.io/eventkit/dxc-server/config"
	"git.multiverse.io/eventkit/dxc-server/constant"
	"github.com/spf13/viper"
	"os"
)

type Loader struct{}

func (b *Loader) LoadConfig(filepath string) (*config.DxcConfig, error) {
	b.setDefault()
	viper.SetConfigFile(filepath)
	if err := viper.ReadInConfig(); err != nil {
		return nil, err
	}
	cfg := &config.DxcConfig{}
	if err := viper.Unmarshal(cfg); err != nil {
		return nil, err
	}
	return cfg, nil
}

func (b *Loader) setDefault() {
	viper.SetDefault("serverAddress", "http://127.0.0.1:18080")
	viper.SetDefault("callbackPort", 18082)
	viper.SetDefault("httpPort", 9999)

	viper.SetDefault("service.expireTimeSeconds", 120)
	viper.SetDefault("service.maxCallbackTimeoutMilliseconds", 5000)
	viper.SetDefault("service.maxCallbackRetryTimes", 3)
	viper.SetDefault("service.maxServiceConsumeMilliseconds", 500)
	viper.SetDefault("service.callbackNodeId", constant.TXN_CALLBACK_NODE_ID)
	viper.SetDefault("service.maxCallbackChannel", constant.DEFAULT_MAX_CALLBACK_CHANNEL)
	viper.SetDefault("service.txnBeginTopicId", constant.TXN_BEGIN_TOPIC_ID)
	viper.SetDefault("service.txnJoinTopicId", constant.TXN_JOIN_TOPIC_ID)
	viper.SetDefault("service.txnEndTopicId", constant.TXN_END_TOPIC_ID)

	viper.SetDefault("job.minIntervalSeconds", 5)
	viper.SetDefault("job.durationSeconds", 300)
	viper.SetDefault("job.batchSyncSize", 50)

	viper.SetDefault("repo.type", "memory")

	viper.SetDefault("log.maxSize", 200)
	viper.SetDefault("log.maxDays", 7)
	viper.SetDefault("log.maxBackups", 7)
	viper.SetDefault("log.console", true)

	viper.SetDefault("metrics.enable", false)
	viper.SetDefault("metrics.reportIntervalSeconds", 5)

	viper.SetDefault("management.enable", false)
	viper.SetDefault("management.abnormalTransactionRecordReportTimeoutMilliseconds", 30*1000)
	viper.SetDefault("management.redundancyAbnormalTransactionRecordReportTimeoutMilliseconds", 30*1000)
	viper.SetDefault("management.pageQueryRedundancyAbnormalTxnRecordTimeoutMilliseconds", 30*1000)

	viper.SetDefault("heartbeat.topicName", "asmHeartBeatMetric")
	viper.SetDefault("heartbeat.intervalSeconds", 30)

	viper.SetDefault("nodeId", os.Getenv(constant.ENV_NODE_ID_KEY))
	viper.SetDefault("instanceId", os.Getenv(constant.ENV_INSTANCE_ID_KEY))
}
